package com.xueyi.starter.timeIterval;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 描述 耗时拦截器
 *
 * @author 俞烨
 * @date 2024-03-18 17
 */
@AllArgsConstructor
@Slf4j
public class TimeIntervalInterceptor implements HandlerInterceptor, WebMvcConfigurer {

    private static final ThreadLocal<TimeInterval> TIME_INTERVAL_THREAD_LOCAL = new ThreadLocal<TimeInterval>();
    private final TimeIntervalProperties timeIntervalProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        TIME_INTERVAL_THREAD_LOCAL.set(DateUtil.timer());
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        long interval = TIME_INTERVAL_THREAD_LOCAL.get().interval();
        TIME_INTERVAL_THREAD_LOCAL.remove();
        log.info("接口: {} ,  总耗时: {}", request.getRequestURI(),
                interval);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(this).addPathPatterns(timeIntervalProperties.getIncludePath())
                .excludePathPatterns(timeIntervalProperties.getExcludePath());
    }
}
